import numpy as np
from modelscope.outputs import OutputKeys
from modelscope.pipelines import pipeline
from PIL import Image


class RecognitionFace:
    inference = None
    def __init__(self):
        self.inference = pipeline(task='face_recognition',model='./model/bubbliiiing/cv_retinafce_recognition', model_revision='v1.0.3')
        print("-------初始化recognition_face---------")

    def test(self):
        img1 = './data/images/face_recognition_1.png'
        img2 = './data/images/face_recognition_2.png'
        img3 = './data/images/me3.jpg'
        img4 = './data/images/me4.jpg'
        emb1 = self.inference(dict(user=img3))[OutputKeys.IMG_EMBEDDING]
        emb2 = self.inference(dict(user=img4))[OutputKeys.IMG_EMBEDDING]
        sim = np.dot(emb1[0], emb2[0])
        print(f'Face cosine similarity={sim:.3f}, img1:{img1}  img2:{img2}')

    def crop_image_from_frame(self, frame, coordinates):
        # 提取坐标并确保它们是整数
        xmin, ymin, xmax, ymax = map(int, coordinates)
        # 检查坐标是否有效
        if xmin < 0 or ymin < 0 or xmax > frame.shape[1] or ymax > frame.shape[0]:
            raise ValueError("Coordinates are out of bounds.")
        # 使用坐标裁剪图像
        cropped_img = frame[ymin:ymax, xmin:xmax]
        return cropped_img

    def get_target_face_coordinate(self, target_face_img, detected_face_collection,frame):
        print("------get_target_face_coordinate--开始检测是否有目标人脸图像------")
        try:
            target_emb = self.inference(dict(user=target_face_img))[OutputKeys.IMG_EMBEDDING]
            for tmp_detected_face_coordinate in detected_face_collection["boxes"]:
                print("tmp_detected_face:",tmp_detected_face_coordinate)
                tmp_face_img = self.crop_image_from_frame(frame, tmp_detected_face_coordinate)
                tmp_face_img = tmp_face_img.astype(np.uint8)
                tmp_image = Image.fromarray(tmp_face_img)
                # 显示图像
                # tmp_image.show()
                # 保存图像
                # tmp_image.save('output_image.png')
                # tmp_emb = self.inference(dict(user='./output_image.png'))[OutputKeys.IMG_EMBEDDING]
                tmp_emb = self.inference(dict(user=tmp_image))[OutputKeys.IMG_EMBEDDING]
                sim = np.dot(target_emb[0], tmp_emb[0])
                print(f'Face cosine similarity={sim:.3f}, img1:{target_face_img}  img2:{tmp_image}')
                if sim > 0.2:
                    print("当前帧中检测到目标人脸")
                    return tmp_detected_face_coordinate
                else:
                    print("当前帧中未检测到目标人脸")
                    return None
        except Exception as e:
            return None


if __name__ == '__main__':
    recognition_face = RecognitionFace()  # 创建类的实例
    recognition_face.test()  # 调用 test 方法
